package org.thirdHero.wx.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.google.common.collect.Maps;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.thirdHero.core.token.UserToken;
import org.thirdHero.core.token.UserTokenManager;
import org.thirdHero.core.util.FastJsonUtil;
import org.thirdHero.wx.dao.UserInfo;
import org.thirdHero.core.util.RedisUtil;

import javax.annotation.Resource;
import java.util.HashMap;

public abstract class BaseController {
    private final Log logger = LogFactory.getLog(BaseController.class);
    @Resource
    RedisUtil redisUtil;
    @Resource
    private WxMaService wxService;
    @Resource
    UserTokenManager userTokenManager;
    /**
     * 小程序用户登录
     * @param body
     * @param code
     * @return
     * @throws WxErrorException
     */
    public UserInfo baseWxUserInfo(String body,String code) throws WxErrorException {
        UserInfo userInfo = FastJsonUtil.parseObject(body, "userInfo", UserInfo.class);
        if (userInfo == null) {
            return null;
        }
        WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
        String sessionKey = result.getSessionKey();
        String openId = result.getOpenid();
        userInfo.setOpenId(openId);
        redisUtil.expire(sessionKey, 7200);
        redisUtil.set(sessionKey, userInfo);
        return userInfo;
    }
    public HashMap<String, Object>  generateToken(String id, Object user){
        UserToken userToken = userTokenManager.generateToken(id,user);
        HashMap<String, Object> result = Maps.newHashMap();
        result.put("token", userToken.getToken());
        result.put("tokenExpire", userToken.getExpireTime().toString());
        result.put("userInfo", user);
        return result;
    }


}

